import os
import time
import requests
# 导入jenkins文件的包
from jenkins import Jenkins

# jenkins的url地址（就是域名，本机就是ip+端口号）
jenkins_url = "http://192.168.***.***:8080/"

# 登录jenkins
server = Jenkins(jenkins_url, username="admin", password="password12##")

# 选择你的jenkins项目名称的地址,这段代码加上jenkins的url就会进入你的ApiTest项目
job_name = "job/API_Test_Driver"

# 发消息的地址
# job_url = server.get_info(job_name)["url"]
# 使用server.server 获取jenkins + url
job_url = server.server + job_name

# 获取最新的构建任务名称，用于拼接后续allure地址
job_last_number = server.get_info(job_name)["lastBuild"]["number"]

# 测试报告allure地址
# report_url = job_url + str(job_last_number) + "/allure"
report_url = job_url + "/" + str(job_last_number) + "/allure"

# 记录时间
job_time = time.strftime("%Y-%m-%d_%H-%M-%S")


def push_message():
    content = {}
    # 服务器执行
    file_path = os.path.dirname(os.getcwd()) + "/outFiles/report/html/export/prometheusData.txt"
    # # 用于本地调试
    # file_path = os.path.dirname(os.getcwd()) + "/outFiles/report/html/export/prometheusData.txt"
    f = open(file_path, "r", encoding="utf-8")
    for line in f.readlines():
        launch_name = line.strip("\n").split()[0]
        num = line.strip("\n").split()[1]
        # 把分割出来的数据组装成键值对 update是一个方法用于组装字典的
        content.update({launch_name: num})
    f.close()
    passed_num = content["launch_status_passed"]  # 通过数量
    failed_num = content["launch_status_failed"]  # 失败数量
    broken_num = content["launch_status_broken"]  # 阻塞数量
    skipped_num = content["launch_status_skipped"]  # 跳过数量
    case_num = content["launch_retries_run"]  # 总数量

    """
    钉钉消息发送，通过webhook发送消息
    """
    webhook = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=ab282e6c-7d53-47c3-805b-55e4f5ef3bb5"
    content = {
        "msgtype": "text",
        "text": {
            "content": "【接口自动化脚本执行结果】: \n【运行总数】：" + case_num
                       + "\n【通过数量】: " + passed_num
                       + "\n【失败数量】: " + failed_num
                       + "\n【阻塞数量】: " + broken_num
                       + "\n【跳过数量】: " + skipped_num
                       + "\n【构建地址】: " + job_url
                       + "\n【报告地址】: " + report_url
                       + "\n【测试时间】: " + job_time
        }
    }
    requests.post(url=webhook, json=content, verify=False)
    # 因为他是https的所以需要加verify = False让他不报警告

push_message()